<?php
// 开启报错信息
ini_set("display_errors", "On");
error_reporting(E_ALL | E_STRICT);

include_once("conn.php");

$page = isset($_GET['page']) ? $_GET['page'] : 1;
$size = isset($_GET['size']) ? $_GET['size'] : 2;


$sql = "SELECT * FROM `articles` limit :page,:size";
// 预处理sql语句
$stmt = $conn->prepare($sql);

// 绑定参数
$pos = ($page-1)*$size;
$stmt->bindParam(":page", $pos, PDO::PARAM_INT);
$stmt->bindParam(":size", $size, PDO::PARAM_INT);

// 执行sql语句
$stmt->execute();
// 获取所有文章
$articles = $stmt->fetchAll();

// print_r($articles);


// 查询有多少篇文章

$sql = "select count(id) as total from articles";
$stmt = $conn->prepare($sql);
$stmt->execute();
$res = $stmt->fetch();
// 文章总条数
$total = $res['total'];

// 总页数 = 向上取整(总条数/每页个数) 
$pages = ceil($total/$size);

?>


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <title></title>

    
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet">

<meta name="theme-color" content="#7952b3">

<style>

  .active{
    color:red;
  }
</style>

</head>
<body>

  <ul>
    <?php
    foreach ($articles as $article) {
    ?>
    <li><a href="/blog.php?id=<?=$article['id']?>"><?=$article['title']?></a></li>
    <?php
    }
    ?>
  </ul>

  <?php
  if($page > 1){
  ?>
  <a href="./list.php?page=<?=$page-1?>&size=<?=$size?>">上一页</a>
  <?php
  } else {
  ?>
  <a href="#">上一页</a>
  <?php
  }
  ?>

  <?php
  for ($i=1; $i<=$pages; $i++) {
  ?>

<a <?php if($i==$page){?> class="active" <?php } ?> href="./list.php?page=<?=$i?>&size=<?=$size?>"><?=$i?></a>
    <?php
    }
    ?>

  <?php
  if($page < $pages){
  ?>
  <a href="./list.php?page=<?=$page+1?>&size=<?=$size?>">下一页</a>
  <?php
  } else {
    ?>
    <a href="#">下一页</a>
    <?php
    }
    ?>
  

  <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.bundle.min.js"></script>
</body>
</html>
